import request from '@/axios/request';

interface StorageListResponse {
  records: Array<{
    storageNumber: string | null
    code: string
    quantity: number
    storageType: string
    remark: string
    operator: string
    createTime: string
    type: string
    description: string
    unit: string
  }>
  total: number
}

interface ApiResponse<T> {
  code: number
  data: T
  message?: string
}

interface RawMaterialData {
  code?: string;
  Code?: string;
  type?: string;
  Type?: string;
  description?: string;
  Description?: string;
  currentstock?: number;
  CurrentStock?: number;
  current_stock?: number;
}

interface MaterialOption {
  code: string;
  type: string;
  description: string;
  currentStock: number;
}

// 获取存储记录列表
export function getStorageList(params: {
  search?: string
  storage_type?: string  // 'I' for in, 'O' for out
  start_date?: string
  end_date?: string
  page?: number
  page_size?: number
}): Promise<StorageListResponse> {
  return request({
    url: '/package-material/storage/list',
    method: 'get',
    params
  }).then(response => {
    // 直接返回分页数据
    return response.data
  })
}

// 新增存储记录
export function addStorageRecord(data: {
  storage_type: string  // 'I' for in, 'O' for out
  storage_number?: string
  material_code: string
  quantity: number
  remark?: string
  operator?: string
}): Promise<ApiResponse<any>> {
  return request({
    url: '/package-material/storage/add',
    method: 'post',
    data
  }).then(response => {
    // 如果能收到响应，就认为是成功的
    return {
      code: 200,
      data: response.data,
      message: 'success'
    }
  }).catch(error => {
    return {
      code: error.response?.status || 500,
      data: null,
      message: error.response?.data?.message || '操作失败'
    }
  })
}

// 获取可用包材列表
export function getMaterialOptions(): Promise<MaterialOption[]> {
  return request({
    url: '/package-material/storage/materials',
    method: 'get'
  }).then(response => {
    const data = response.data as RawMaterialData[];
    // 确保数据格式正确
    return data.map((item: RawMaterialData) => {
      // 尝试获取库存值
      let stock = 0;
      if ('currentstock' in item && item.currentstock !== undefined) stock = item.currentstock;
      else if ('CurrentStock' in item && item.CurrentStock !== undefined) stock = item.CurrentStock;
      else if ('current_stock' in item && item.current_stock !== undefined) stock = item.current_stock;
      
      return {
        code: item.code || item.Code || '',
        type: item.type || item.Type || '',
        description: item.description || item.Description || '',
        currentStock: Number(stock)
      };
    });
  });
} 